package oboe.controllers.soundController;

import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;

import oboe.core.Oboe;

import flash.Vector;

class ManagedSound
{
private var sound:Sound;
private var channels:Vector< ManagedChannel >;
private var onEnd:Function;
private var name:String;
private var soundClass:String;

public function new( sound:Sound, onEnd:Function, name:String, soundClass:String )
{
	this.sound = sound;
	this.onEnd = onEnd;
	this.name = name;
	this.soundClass = soundClass;
	this.channels = new Vector();
}

public function getChannelCount():Int
{
	return channels.length;
}

public function getSoundClass():String
{
	return this.soundClass;
}

public function removeChannel( channel:ManagedChannel ):Void
{
	var i:Int = channels.indexOf( channel );
	if( i == -1 ) return;
	channels[i] = channels[ channels.length-1 ];
	channels.pop();
}

public function play( pos:Float, loops:Int, transform:SoundTransform=null ):Void
{
	if( Oboe.flags["NO_SOUND"] || !this.sound ) return;
	this.channels.push( new ManagedChannel( this, pos, loops, transform, this.onEnd ) );
}

public function getName():String
{
	return this.name;
}

public function getSound():Sound
{
	return this.sound;
}

public function stop():Void
{
	if( !this.channels.length ) return;
	var currentChannel:ManagedChannel = this.channels.pop();
	currentChannel.stop( true );
}

public function stopAll():Void
{
	for each( var channel:ManagedChannel in this.channels )
	{
	channel.stop( true );
	}
	
	this.channels.length = 0;
}

public function pause():Void
{
	for each( var channel:ManagedChannel in this.channels )
	{
	channel.stop( false );
	}
}

public function resumeAfter( timeElapsed:Float ):Void
{
	for( var i:Int=0; i<this.channels.length; ++i )
	{
	this.channels[i].resumeAfter( timeElapsed );
	}
}
}